﻿using PhotoGallery.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Helpers;
using System.Web.Hosting;
using PagedList;
using System.IO;
using PhotoGallery.Models.Utils;
using PhotoGallery.Models.ViewModels;
using PhotoGallery.Infrastructure;

namespace PhotoGallery.Controllers
{
    [Authorize]
    //[DataRequired]
    public class PhotoController : BaseController
    {
        [RequiredAlbumID]
        public ActionResult Index(int? albumID)
        {
            return RedirectToAction("List");
        }

        [RequiredAlbumID]
        public ActionResult Details(int? id, int? albumID)
        {
            if (!id.HasValue)
            {
                return RedirectToAction("Index");
            }

            AlbumInfo album = new AlbumsModel().Get(albumID ?? default(int));
            return View(new PhotosModel(album).Get(id ?? default(int)));
        }

        public ActionResult Create()
        {
            if (Request.UrlReferrer != null)
            {
                TempData["backUrl"] = Request.UrlReferrer.ToString();
                ViewBag.backUrl = Request.UrlReferrer.ToString();
            }
            else
            {
                ViewBag.backUrl = Url.Action("Index");
            }
            return View(new PhotoInfo());
        }

        [HttpPost]
        public ActionResult Create(PhotoInfo photo, int albumID, HttpPostedFileBase[] files)
        {
            ViewBag.backUrl = TempData["backUrl"];
            TempData.Keep();
            if (files.FirstOrDefault() != null)
            {
                if (ModelState.IsValid)
                {
                    AlbumInfo album = new AlbumsModel().Get(albumID);
                    PhotosModel model = new PhotosModel(album);
                    foreach (HttpPostedFileBase file in files)
                    {
                        if (FileValidation.IsValid(file, new List<string>(){
                            ".jpg",".jpeg",".png",".bmp","tif"
                        }))
                        {
                            model.Create(photo, file);
                        }
                    }
                    return RedirectToAction("index");
                }
            }
            else
            {
                ModelState.AddModelError("", ErrorMessages.noFiles);
            }

            return View(photo);
        }

        [RequiredAlbumID]
        public ActionResult Edit(int? id, int? albumID)
        {
            if (!id.HasValue)
            {
                return RedirectToAction("Index");
            }

            if (Request.UrlReferrer != null)
            {
                TempData["backUrl"] = Request.UrlReferrer.ToString();
                ViewBag.backUrl = Request.UrlReferrer.ToString();
            }
            else
            {
                ViewBag.backUrl = Url.Action("Index");
            }
            AlbumInfo album = new AlbumsModel().Get(albumID ?? default(int));
            PhotoInfo photo = new PhotosModel(album).Get(id ?? default(int));
            if (photo == null)
                return Redirect("Index");

            return View(photo);
        }

        [HttpPost]
        public ActionResult Edit(PhotoInfo photo, HttpPostedFileBase file, int albumID)
        {
            ViewBag.backUrl = TempData["backUrl"];
            TempData.Keep();
            if (ModelState.IsValid)
            {
                try
                {
                    AlbumInfo album = new AlbumsModel().Get(albumID);
                    PhotosModel model = new PhotosModel(album);
                    if (FileValidation.IsValid(file, new List<string>(){
                            ".jpg",".jpeg",".png",".bmp","tif"
                    }))
                    {
                        model.Update(photo, file);
                    }
                    return Redirect(ViewBag.backUrl);
                }
                catch (Exception ex)
                {
                    //error msg for failed edit in XML file
                    ModelState.AddModelError("", "Error editing record. " + ex.Message);
                }
            }

            return View(photo);
        }

        [RequiredAlbumID]
        public ActionResult Delete(int? id, int? albumID)
        {
            if (!id.HasValue)
            {
                return RedirectToAction("Index");
            }

            TempData["backUrl"] = Request.UrlReferrer.ToString();
            ViewBag.backUrl = Request.UrlReferrer.ToString();

            AlbumInfo album = new AlbumsModel().Get(albumID ?? default(int));
            PhotoInfo photo = new PhotosModel(album).Get(id ?? default(int));
            if (photo == null)
                return RedirectToAction("Index");

            return View(photo);
        }
        
        [HttpPost]
        public ActionResult Delete(int id, int albumID, PhotoInfo photo)
        {
            ViewBag.backUrl = TempData["backUrl"];
            TempData.Keep();

            AlbumInfo album = new AlbumsModel().Get(albumID);
            PhotosModel model = new PhotosModel(album);
            
            try
            {
                model.Delete(photo);
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMsg = "Error deleting record. " + ex.Message;
                return View(photo);
            }
        }

        [RequiredAlbumID]
        public ActionResult Preview(int? albumID)
        {
            AlbumInfo album = new AlbumsModel().Get(albumID ?? -1);
            return View(new PhotosModel(album).Get());
        }

        [RequiredAlbumID]
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
        public ActionResult List(int? albumID, int? page)
        {
           
            PhotoViewModel viewModel = new PhotoViewModel();
            viewModel.Album = new AlbumsModel().Get(albumID ?? -1);
            viewModel.Photos = new PhotosModel(viewModel.Album).Get(); 

            var pageNumber = page ?? 1;
            var onePageOfProducts = viewModel.Photos.ToPagedList(pageNumber, 8);

            ViewBag.OnePageOfProducts = onePageOfProducts;
            return View(viewModel);
        }

        public ActionResult Download(string file = "")
        {

            var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            var mimeType = "image/jpeg";
            var fileDownloadName = Path.GetFileName(file);
            return File(fileStream, mimeType, fileDownloadName);
        }

        [RequiredAlbumID]
        public ActionResult View(int id, int albumID)
        {
            AlbumInfo album = new AlbumsModel().Get(albumID);
            return View(new PhotosModel(album).Get(id));
        }
    }
}
